package com.lxl.config;

import com.lxl.common.CommonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @Description 切面配置日志信息
 * @Date 2021/12/1 11:35
 * @Created by LXLDEMO
 */
@Aspect
@Component
public class LogAopConfig {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Pointcut("(execution(public * com.lxl.controller..*.*(..)))")
    public void logCut(){

    }

    /**
     *
     * @param joinPoint
     */
    @Before("logCut()")
    public void logStart(JoinPoint joinPoint){
        log.info("==============接口日志开始记录=======START=======");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (CommonUtil.isEmpty(requestAttributes)){
            log.warn("============= requestAttributes为null =======");
            return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        if (CommonUtil.isEmpty(request)){
            log.warn("============= request =======");
            return;
        }
        //获得请求路径
        log.info("url={}",request.getRequestURL());
        //method
//        log.info("method={}",request.getMethod());
        //获得ip
//        log.info("ip={}",request.getRemoteAddr());
        //获得参数
        log.info("params={}",joinPoint.getArgs());
        //获得类方法
//        log.info("classMethod={}",joinPoint.getSignature().getDeclaringTypeName()+joinPoint.getSignature().getName());
    }

    /**
     *
     */
    @AfterReturning("logCut()")
    public void logEnd(){
        log.info("==============接口日志记录完成=======END=======");
    }

    /**
     * 记录接口用时
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("logCut()")
    public Object logAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        log.info("接口用时{}毫秒",(endTime - startTime));
        return result;
    }
}
